﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class admintractor_UserEdit : System.Web.UI.Page
{
    private RoleBusiness role = new RoleBusiness();
    private UserBusiness user = new UserBusiness();
    private int id = Helper.getQuery("id");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindRole();
            bindPosition();
            if (id > 0)
            {
                but_add.Text = "Sửa";
                UsersEntities item = user.getItem(id);
                txtUsername.Visible = false;
                txtPassword.Visible = false;
                lb_User.Visible = false;
                lb_Pass.Visible = false;
                txtEmail.Text = item._email;
                txtMessenger.Text = item._messenger;
                txtName.Text = item._name;
                txtBirthday.Text = item._birthday;
                if (item._gender.Trim().Equals("True"))
                { rb_male.Checked = true;}
                else
                { rb_female.Checked = true; }
                if (item._display.Trim().Equals("True"))
                { cbView.Checked = true; }
                if (item._status.Trim().Equals("True"))
                { cbStatus.Checked = true; }
                txt_Address.Text = item._address;
                txtMobile.Text = item._mobile;
                dropRole.SelectedValue = item._roleID.ToString().Trim();
                string position = item._position.Substring(0,item._position.Length-1);
                //Response.Write(position);
                string[] ps = position.Split('@');// Response.Write(ps.Length);
                this.checkposition(item._roleID, ps);
            }
            else
            {
                but_add.Text = "Thêm mới";
                txtUsername.Visible = true;
                txtPassword.Visible = true;
                lb_Pass.Visible = true;
                lb_User.Visible = true;
            }
        }
    }
    public void bindRole()
    {
        ArrayList items = role.getRole();
        dropRole.DataSource = items;
        dropRole.DataTextField = "_name";
        dropRole.DataValueField = "_id";
        dropRole.DataBind();
        dropRole.Items.Add(new ListItem("-Chọn một-", 0.ToString()));
        dropRole.SelectedValue = 0.ToString();
        
    }
    public void bindPosition()
    {
        int l = Option.menu.Length / 3;
        for (int i = 0; i < l; i++)
        {
            ListItem item = new ListItem(Option.menu[i, 2].ToString(), Option.menu[i, 0].ToString());
            cbl_position.Items.Add(item);
            item = null;
        }
    }
    public void checkposition(int values,string[] position)
    {
        if (values == 1)
        {
            for (int i = 0; i < cbl_position.Items.Count; i++)
            {
                cbl_position.Items[i].Selected = true;
            }
            cbl_position.Enabled = false;
        }
        else
        {
            cbl_position.Enabled = true;
            if (position != null && !position.Equals(""))
            {
                for (int i = 0; i < position.Length; i++)
                {
                    for (int j = 0; j < cbl_position.Items.Count; j++)
                    {
                        if (position[i].Equals(cbl_position.Items[j].Value))
                        {
                            cbl_position.Items[j].Selected = true;
                            break;
                        }
                    }
                }
            }
        }
    }
    protected void dropRole_SelectedIndexChanged(object sender, EventArgs e)
    {
        int value=int.Parse(dropRole.SelectedValue.Trim());
        string[] position={};
        this.checkposition(value, position);
    }

    public string position()
    {
        string tmp = "";
        if (dropRole.SelectedValue.Trim().Equals("1"))
        {
            tmp = "all";
        }
        else
        {
            for (int i = 0; i < cbl_position.Items.Count; i++)
            {
                if (cbl_position.Items[i].Selected == true)
                {
                    tmp += cbl_position.Items[i].Value + "@";
                }
            }
        }
        return tmp;
    }
    public UsersEntities getUser()
    {
        UsersEntities us = new UsersEntities();
        us._name = txtName.Text.Trim();
        us._email = txtEmail.Text.Trim();
        us._address = txt_Address.Text.Trim();
        us._messenger = txtMessenger.Text.Trim();
        us._mobile = txtMobile.Text.Trim();
        us._roleID = int.Parse(dropRole.SelectedValue.Trim());
        us._gender = rb_male.Checked ? "1" : "0";
        us._display = cbView.Checked ? "1" : "0";
        us._status = cbStatus.Checked ? "1" : "0";
        us._position = this.position();
        us._birthday = txtBirthday.Text.Trim();
        return us;
    }
    public bool checkMail()
    {
        bool flat = true;
        string MatchEmailPattern =
                    @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
             + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
             + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?
				[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
             + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
        System.Text.RegularExpressions.Regex c = new System.Text.RegularExpressions.Regex(MatchEmailPattern, System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);
        if (!c.IsMatch(txtEmail.Text.Trim()))
        {
            flat = false;
        }
        return flat;
    }

    protected void but_add_Click(object sender, EventArgs e)
    {
        if (id > 0)
        {
            if (txtEmail.Text.Trim().Equals("") || dropRole.SelectedValue.Trim().Equals("0"))
            {
                lbError.Text = "Nhập thiếu thông tin";
            }
            else
            {
                if (checkMail())
                {
                    UsersEntities us = this.getUser();
                    us._userID = id;
                    if (user.edit(us))
                    {
                        Response.Redirect("User.aspx");
                    }
                    else
                    {
                        lbError.Text = "Xẩy ra nỗi trong quá trình thực hiện";
                    }
                }
                else
                {
                    lbError.Text = "Hòm thư không hợp lệ";
                }
            }
        }
        else
        {
            if (txtUsername.Text.Trim().Equals("") || txtPassword.Text.Trim().Equals("")||txtEmail.Text.Trim().Equals("") || dropRole.SelectedValue.Trim().Equals("0"))
            {
                lbError.Text = "Nhập thiếu thông tin";
            }
            else
            {
                if (checkMail())
                {
                    if (!user.checkUser(txtUsername.Text.Trim(), ""))
                    {
                        lbError.Text = "Tên đăng nhập đã tồn tại";
                    }
                    else
                    {
                        UsersEntities us = this.getUser();
                        us._userName = txtUsername.Text.Trim();
                        us._pass = Utility.EncodePass(txtPassword.Text.Trim());
                        if (user.add(us))
                        {
                            Response.Redirect("User.aspx");
                        }
                        else
                        {
                            lbError.Text = "Xẩy ra nỗi trong quá trình thực hiện";
                        }
                    }
                }
                else
                {
                    lbError.Text = "Hòm thư không hợp lệ";
                }

            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("User.aspx");
    }
}
